package com.fs.sys.entityservice;

import com.fs.sys.bean.dto.RoleAppDTO;
import com.fs.sys.bean.query.RoleAppQuery;
import com.fs.sys.bean.req.AppRoleAddReq;
import com.fs.sys.bean.req.RoleAppAddReq;
import com.fs.common.base.service.BaseService;
import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 角色应用关系服务接口 
 * @author Coder Generator 2025-06-10 10:58:46 
 **/
public interface RoleAppEntityService extends BaseService<RoleAppDTO, RoleAppQuery> {
    /**
     * 更新应用角色关系
     * @param req 更新请求
     */
    default void updateAppRole(AppRoleAddReq req) {
        // 先删除后添加
        String appId = req.getAppId();
        this.deleteBuilder()
                .eq("app_id", appId)
                .delete();

        List<RoleAppDTO> list = new ArrayList<>(16);
        req.getRoleIds().forEach(roleId -> {
            RoleAppDTO dto = new RoleAppDTO();
            list.add(dto);
            dto.setAppId(appId);
            dto.setRoleId(roleId);
        });
        this.insert(list);
    }

    /**
     * 添加角色应用
     * @param req 请求参数
     */
    default void addRoleApps(RoleAppAddReq req) {
        List<String> appIds = this.queryBuilder()
                .eq("role_id", req.getRoleId())
                .queryAndConvert(RoleAppDTO::getAppId);
        List<RoleAppDTO> list = req.getAppIds().stream()
                .filter(appId -> !appIds.contains(appId))
                .map(appId -> {
                    RoleAppDTO dto = new RoleAppDTO();
                    dto.setRoleId(req.getRoleId());
                    dto.setAppId(appId);
                    return dto;
                }).toList();
        if (CollectionUtils.isEmpty(list)) {
            return;
        }

        this.insert(list);
    }
}